package com.wangshuo.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wangshuo.common.JwtHelper;
import com.wangshuo.config.Result;
import com.wangshuo.entity.Acount;
import com.wangshuo.entity.Admin;
import com.wangshuo.entity.User;
import com.wangshuo.service.AdminService;
import com.wangshuo.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin")
public class AccountController {
    @Resource
    private AdminService adminService;
    @Resource
    private UserService userService;
    @Resource
    private JwtHelper jwtHelper;

    @PostMapping("/login")
    public Result login(@RequestBody Acount acount) {
        Result res = null;
        if (acount.getRole().equals("ADMIN")) {
            res = adminService.login(acount);
        } else if (acount.getRole().equals("USER")) {
            res = userService.login(acount);
        }
        return res;

    }
    @GetMapping("/info")
    public Result info(HttpServletRequest httpServletRequest){

        Long uid=jwtHelper.getUserId(httpServletRequest.getHeader("token"));
        Admin admin=adminService.getById(uid);
        return Result.ok(admin);
    }
    @GetMapping("/userinfo")
    public Result userinfo(HttpServletRequest httpServletRequest){

        Long uid=jwtHelper.getUserId(httpServletRequest.getHeader("token"));
        User user=userService.getById(uid);
        return Result.ok(user);
    }
    @PostMapping("/register")
    public Result register(@RequestBody Acount acount){
        Result res = null;
        if (acount.getRole().equals("ADMIN")) {
            res = adminService.register(acount);
        } else if (acount.getRole().equals("USER")) {
            res = userService.register(acount);
        }
        return res;
    }
    @PostMapping("/addandupdate")
    public Result addandupdate(@RequestBody Admin admin){
        adminService.saveOrUpdate(admin);
        return Result.ok("成功");
    }
    @PostMapping("/useraddandupdate")
    public Result useraddandupdate(@RequestBody User user){
        userService.saveOrUpdate(user);
        return Result.ok("成功");
    }
    @GetMapping("/list")
    public Result list(@RequestParam Integer pageNum,@RequestParam Integer pageSize,@RequestParam String keyword){
        IPage<Admin> page=new Page<>(pageNum,pageSize);
        IPage<Admin> list=adminService.getpage(page,keyword);
        return Result.ok(list);

    }
    @GetMapping("/delete")
    public Result delete(@RequestParam Integer id){
         adminService.removeById(id);
    return Result.ok("成功");
    }


}
